package cn.darkhorse.mesadmin.controller.mysql;

import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.ruoyi.common.core.domain.AjaxResult;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/mysql")
public class MySqlController {
    private static Map<String, String> columnTypeMap = new HashMap<>();
    private static Set<String> lengthlessSet = new HashSet<>();

    static {
        columnTypeMap.put("bigint", "bigint");
        columnTypeMap.put("nvarchar", "varchar");

        lengthlessSet.add("datetime2");
        lengthlessSet.add("datetime");
    }

    @Data
    @Accessors(chain = true)
    private class Field {
        private String columnName;
        private String columnType;
        private String columnLength;
        private String columnComment;

        public Field(String columnName, String columnType, String columnLength, String columnComment) {
            this.columnName = columnName;
            this.columnType = columnType;
            this.columnLength = columnLength;
            this.columnComment = columnComment;
        }

        private String getFieldString() {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format(" `%s` ", columnName));

            if (lengthlessSet.contains(columnType)) {
                sb.append(String.format(" %s", columnTypeMap.get(columnType)));
            }else {
                sb.append(String.format(" %s(%s)", columnType, getLength()));
            }

            if ("id".equals(columnName)) {
                sb.append(String.format(" NOT NULL AUTO_INCREMENT COMMENT '%s',", columnComment));
            }else {
                sb.append(String.format(" DEFAULT NULL COMMENT '%s',", columnComment));
            }

            return "";
        }

        private String getLength() {
            if ("-1".equals(columnLength)) {
                return "8000";
            }else {
                return columnLength;
            }
        }
    }

    @RequestMapping("/g")
    public AjaxResult test() {
        String tableName = "alarm_parameter_settings";

        String sql = String.format("SELECT  \n" +
                "    col.name AS ColumnName,  \n" +
                "    ty.name AS ColumnType,  \n" +
                "    col.max_length AS ColumnLength,  \n" +
                "    ep.value AS ColumnComment  \n" +
                "FROM sys.columns col  \n" +
                "JOIN sys.types ty ON col.user_type_id = ty.user_type_id  \n" +
                "LEFT JOIN sys.extended_properties ep ON ep.major_id = col.object_id AND ep.minor_id = col.column_id AND ep.name = 'MS_Description'  \n" +
                "WHERE OBJECT_ID('%s') = col.object_id", tableName);

        List<Map<String, Object>> maps = SqlRunner.db().selectList(sql);
           StringBuilder create = new StringBuilder(String.format("CREATE TABLE `%s` (", tableName));
        String fieldStr = " %s";
        StringBuilder end = new StringBuilder("  PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='%s';");

        StringBuilder fieldSb = new StringBuilder();

        maps.forEach(map-> {
            Field field = new Field(map.get("ColumnName").toString()
                    , map.get("ColumnType").toString()
                    , map.get("ColumnLength").toString()
                    , map.get("ColumnComment").toString());
            fieldSb.append(field.getFieldString());
        });

        return AjaxResult.success(create + fieldSb.toString()
                + end);
    }
}
